package com.dfdchem.imd.kaiwu.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.activity.MainActivity;
import com.dfdchem.imd.kaiwu.activity.base.BaseFragment;
import com.dfdchem.imd.kaiwu.constant.RouterPath;
import com.dfdchem.imd.kaiwu.interfaces.OnHttpResponseListener;
import com.dfdchem.imd.kaiwu.manager.DataManager;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.model.AppPublish;
import com.dfdchem.imd.kaiwu.model.Resp;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.JSON;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;
import com.dfdchem.imd.kaiwu.util.VersionUtil;
import com.kongzue.kongzueupdatesdk.v3.UpdateUtil;
import com.makeramen.roundedimageview.RoundedImageView;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

public class ProfileFragment extends BaseFragment implements OnHttpResponseListener, View.OnClickListener, OnRefreshListener {
    private static final String TAG = "ProfileFragment";

    private RoundedImageView avatar;
    private TextView versionTextView;
    private TextView userNameTextView;
    private TextView phoneTextView;

    private LinearLayout user_profile_ll;
    private LinearLayout profile_grid_message;
    private LinearLayout profile_grid_feedback;
    private LinearLayout profile_grid_setting;
    private RelativeLayout profile_item_update;
    private RelativeLayout profile_item_exit;
    private RelativeLayout profile_item_about;
    private RelativeLayout profile_item_setting;
    private RelativeLayout profile_item_feedback;
    private RelativeLayout profile_item_message;
    private RelativeLayout profile_item_help;

    private RefreshLayout refreshLayout;

    private User user;

    private MainActivity mainActivity;
    private UpdateUtil updateUtil;

    private static final int request_code_get_user_info = 1;
    private static final int request_code_version_check = 2;


    public ProfileFragment() {
        super();
    }

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_profile,
                container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 初始化MainActivity
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        }

        initData();
        initEvent();
    }

    private void initView(View view) {
        user_profile_ll = view.findViewById(R.id.user_profile_ll);

        profile_grid_message =(LinearLayout) view.findViewById(R.id.profile_grid_message);
        profile_grid_feedback =(LinearLayout) view.findViewById(R.id.profile_grid_feedback);
        profile_grid_setting = view.findViewById(R.id.profile_grid_setting);

        avatar = (RoundedImageView) view.findViewById(R.id.user_avatar);
        versionTextView = (TextView) view.findViewById(R.id.version_textview);
        userNameTextView = (TextView) view.findViewById(R.id.user_name);
        phoneTextView = (TextView) view.findViewById(R.id.user_phone);

        // 点击列表
        profile_item_update =(RelativeLayout) view.findViewById(R.id.profile_item_update);
        profile_item_exit =(RelativeLayout) view.findViewById(R.id.profile_item_exit);
        profile_item_about =(RelativeLayout) view.findViewById(R.id.profile_item_about);
        profile_item_setting =(RelativeLayout) view.findViewById(R.id.profile_item_setting);
        profile_item_feedback =(RelativeLayout) view.findViewById(R.id.profile_item_feedback);
        profile_item_message =(RelativeLayout) view.findViewById(R.id.profile_item_message);
        profile_item_help =(RelativeLayout) view.findViewById(R.id.profile_item_help);

        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);

    }

    private void initData() {
        versionTextView.setText(VersionUtil.getAppVersionName(getActivity()));

        refreshData();
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void initUserInfo(User user){
        if (user == null) return;
        userNameTextView.setText(user.getUserName());
        phoneTextView.setText(user.getPhone());
        String avatar_url = user.getAvatar();
        if (isAdded() && getActivity() != null) {
            if (StringUtil.isEmpty(avatar_url)) {
                avatar.setImageDrawable(getActivity().getDrawable(R.drawable.ic_default_avatar));
            } else {
                // 适配内网地址
                if (avatar_url.startsWith(RequestUtil.url_file_short)) {
                    avatar_url = RequestUtil.URL_BASE_API + avatar_url;
                }

                new GlideManager(this).load(avatar, avatar_url);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        user = DataManager.getInstance().getUser();
        initUserInfo(user);
    }

    private void initEvent() {
        user_profile_ll.setOnClickListener(this);

        profile_grid_message.setOnClickListener(this);
        profile_grid_feedback.setOnClickListener(this);
        profile_grid_setting.setOnClickListener(this);

        profile_item_update.setOnClickListener(this);
        profile_item_exit.setOnClickListener(this);
        profile_item_about.setOnClickListener(this);
        profile_item_setting.setOnClickListener(this);
        profile_item_feedback.setOnClickListener(this);
        profile_item_message.setOnClickListener(this);
        profile_item_help.setOnClickListener(this);

        refreshLayout.setOnRefreshListener(this);
    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
        Log.d(TAG, "onHttpResponse requestCode:" + requestCode + " resultJson:" + resultJson);
        if (requestCode == request_code_version_check) {
            mainActivity.dismissProgressDialog();
        }
        if (e != null) {
            if (refreshLayout.isRefreshing()) {
                refreshLayout.finishRefresh(250);
            }
            Toast.makeText(getActivity(), "请求失败，" + e.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        switch (requestCode) {
            case request_code_get_user_info:
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh(250);
                }
                Resp<User> respUser = JSON.parseResp(resultJson, User.class);
                if (respUser == null || respUser.getCode() != 200) {
                    Toast.makeText(getActivity(), respUser != null ? respUser.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                User user = respUser.getData();
                if (user == null) {
                    Toast.makeText(getActivity(), "解析异常", Toast.LENGTH_LONG).show();
                    return;
                }
                DataManager.getInstance().saveUser(user);
                initUserInfo(user);
                break;
            case request_code_version_check:
                Resp<AppPublish> respAppPublish = JSON.parseResp(resultJson, AppPublish.class);
                if (respAppPublish == null || respAppPublish.getCode() != 200) {
                    Toast.makeText(getActivity(), respAppPublish != null ? respAppPublish.getMsg() : "请求失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                AppPublish appPublish = respAppPublish.getData();
                if (appPublish == null) {
                    Toast.makeText(getActivity(), "目前已经是最新版本", Toast.LENGTH_LONG).show();
                    return;
                }

                // 适配内网地址
                if (appPublish.getPackageUrl().startsWith("/Fe/Files/Index")) {
                    appPublish.setPackageUrl(RequestUtil.URL_BASE_API + appPublish.getPackageUrl());
                }

                //初始化
                if (updateUtil == null) {
                    updateUtil = new UpdateUtil(getActivity());
                }

                updateUtil.setOnUpdateStatusChangeListener(null)
                        .showDownloadNotification("正在下载更新", "正在下载更新 " +  appPublish.getTitle() + "...")
                        .showDownloadProgressDialog("正在下载更新", "后台下载", "取消")
                        .start(appPublish.getPackageUrl(),                       //开始下载
                                "发现更新",
                                appPublish.getDes(),
                                "确定",
                                "取消",
                                null,
                                false
                        );
                break;

        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.user_profile_ll:
                mainActivity.toActivity(RouterPath.PROFILE_ACTIVITY);
                break;
            case R.id.profile_item_update:
                mainActivity.showProgressDialog("正在检查更新，请稍后...");
                mainActivity.runThread(TAG + "getAppUpdate", new Runnable() {
                    @Override
                    public void run() {
                        AppPublish appPublish = new AppPublish();
                        appPublish.setPackageName(VersionUtil.getPackageName(getActivity()));
                        appPublish.setVersionCode(VersionUtil.getAppVersionCode(getActivity()));
                        RequestUtil.versionCheck(appPublish, request_code_version_check, ProfileFragment.this);
                    }
                });

                break;
            case R.id.profile_item_exit:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("退出登录：");
                builder.setMessage("确定退出吗?");
                builder.setIcon(R.drawable.icon_info);
                builder.setPositiveButton("是的", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mainActivity.logout();
                    }
                });
                builder.setNegativeButton("我在想想", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builder.create().show();
                break;

            case R.id.profile_item_about:
                mainActivity.toActivity(RouterPath.ABOUT_ACTIVITY);
                break;
            case R.id.profile_item_setting:
            case R.id.profile_grid_setting:
                mainActivity.toActivity(RouterPath.ENV_SETTING_ACTIVITY);
                break;
            case R.id.profile_grid_feedback:
            case R.id.profile_item_feedback:
                mainActivity.toActivity(RouterPath.FEEDBACK_ACTIVITY);
                break;
            case R.id.profile_grid_message:
            case R.id.profile_item_message:
                mainActivity.toActivity(RouterPath.MESSAGE_ACTIVITY);
                break;
            case R.id.profile_item_help:
                Uri uri = Uri.parse(RequestUtil.URL_HELP);
                mainActivity.handleScheme(uri);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        if (updateUtil != null) {
            updateUtil.recycle();
            updateUtil = null;
        }
        super.onDestroy();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    private void refreshData(){
        // 更新本地存储的用户信息
        mainActivity.runThread(TAG + "getUserInfo", new Runnable() {
            @Override
            public void run() {
                RequestUtil.getUserInfo(request_code_get_user_info, ProfileFragment.this);
            }
        });
    }
}
